﻿// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT.
// Copyright (C) Leszek Pomianowski and WPF UI Contributors.
// All Rights Reserved.

using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Windows.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.Protocol;
using NuGetManager.CommunityToolkit.NuGet;
// ReSharper disable All

namespace PackageManager.ViewModels;

public partial class PackageManagerViewModel : ObservableObject
{
    private static NuGetPackageManager _manager;
    [ObservableProperty] private ObservableCollection<NugetPackageSearchItem> packages=new()
    {
        new()
    };

    public PackageManagerViewModel()
    {
        var installFolder = $"{AppDomain.CurrentDomain.BaseDirectory}modules/";
        var source = "https://api.nuget.org/v3/index.json";
        _manager = new NuGetPackageManager(installFolder, source);
        OnLoadCommand = new RelayCommand(OnLoad);
        DownloadCommand = new RelayCommand<PackageIdentity>(Download);
    }

    private void OnLoad()
    {
        Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
        Task.Run(() =>
        {
            var packages = _manager.SearchPackages("json").Result;
            
            var result = from p in packages
                select new NugetPackageSearchItem(p);

            dispatcher.Invoke(() =>
            {
                foreach (var nugetPackageSearchItem in result)
                {
                    this.Packages.Add(nugetPackageSearchItem);
                }
            });
        });
    }

    public ICommand OnLoadCommand { get; }

    private static void Download(PackageIdentity? pi)
    {
        Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
        Task.Run(() =>
        {
        _manager.DownloadPackageAsync(pi.Id,pi.Version.ToString());
        });
    }
    
    public ICommand DownloadCommand { get; } 
}